package cn.windy.samary.module.file.service.impl;

import cn.windy.samary.module.abstracts.service.impl.AbstractServiceImpl;
import cn.windy.samary.module.file.entity.FileInfo;
import cn.windy.samary.module.file.mapper.FileInfoMapper;
import cn.windy.samary.module.file.service.IFileInfoService;
import cn.windy.samary.utils.ResourceBundleUtil;
import org.apache.commons.lang.StringUtils;
import org.n3r.idworker.Sid;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zyl
 * @date 2018/4/11 15:37
 */
@Service
public class FileInfoServiceImpl extends AbstractServiceImpl<FileInfo> implements IFileInfoService {


    @Resource
    private Sid sid;
    @Resource
    private FileInfoMapper fileInfoMapper;

    /**
     * @param fileName   文件名
     * @param fileType   文件类型
     * @param moduleType 模块类型
     * @param files      文件
     * @param type       返回类型，type不为空时，返回图片请求路径，流方式加载
     * @return 。
     * @throws IOException e
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object[] fileUpload(String fileName, String fileType, String moduleType, MultipartFile[] files, String type)
            throws IOException {
        String path = ResourceBundleUtil.getString("system", "fileupload.path");
        if (StringUtils.isEmpty(moduleType)) {
            return null;
        }
        if (StringUtils.isEmpty(fileType)) {
            return null;
        }
        File filePath = new File(path, moduleType + "/" + fileType);
        boolean b = filePath.mkdirs();
        boolean isName = StringUtils.isNotEmpty(fileName);
        List<String> fileNames = new ArrayList<>();
        if (files != null && files.length > 0) {
            int m = 0;
            for (MultipartFile file : files) {
                String oldName = file.getOriginalFilename();
                String newName = sid.nextShort();
                String suffix = "";
                int index = oldName.lastIndexOf(".");
                if (index > 0) {
                    newName += oldName.substring(index);
                    suffix = oldName.substring(index + 1);
                }
                if (isName) {
                    oldName = fileName;
                    if (StringUtils.isNotEmpty(suffix)) {
                        oldName += "." + suffix;
                    }
                }
                file.transferTo(new File(filePath, newName));

                FileInfo info = new FileInfo(oldName, newName, fileType,
                        moduleType + "/" + fileType + "/" + newName, suffix);
                int i = insertSelective(info);
                if (StringUtils.isNotEmpty(type)) {
                    fileNames.add("api/imgView/" + info.getId());
                } else {
                    fileNames.add(moduleType + "/" + fileType + "/" + newName);
                }
            }
        }
        return fileNames.toArray();
    }

    /**
     * 上传文件
     *
     * @param file
     * @param parentDirectory 文件要保存的父级目录
     * @param fileName        文件名，如果为null，将随机生成
     * @param isRandom        是否随机命名，若为false,且fileName为null，将使用原文件名
     * @return 新文件名，不包含路径
     * @throws IOException
     */
    @Override
    public String fileUpload(MultipartFile file, File parentDirectory, String fileName, boolean isRandom)
            throws IOException {
        parentDirectory.mkdirs();
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.contains(".") ? originalFilename.substring(originalFilename.lastIndexOf("."))
                : "";
        boolean isFileName = StringUtils.isNotEmpty(fileName);
        if (!file.isEmpty() && file.getSize() != 0L) {
            fileName = isFileName ? fileName + suffix : sid.nextShort() + suffix;
            if (!isRandom && !isFileName) {
                fileName = file.getOriginalFilename();
            }
            File dest = new File(parentDirectory, fileName);
            if (dest.exists() && dest.isFile()) {
                dest.delete();
            }
            file.transferTo(dest);
            return fileName;
        }
        return null;
    }


    /**
     * 目录递归删除
     *
     * @param file 目录
     * @throws Exception
     */
    public void deleteDirectory(File file) {
        if (file != null) {
            File[] files = file.listFiles();
            for (File file1 : files) {
                if (file1.isDirectory()) {
                    deleteDirectory(file1);
                }
                file1.delete();
            }
        }
    }

    // 1416556556
    public static void main(String[] args) throws Exception {

    }
}
